package com.agriculture.service;

import com.agriculture.common.Response;
import com.agriculture.domain.User;
import com.agriculture.dto.auth.LoginDTO;
import com.agriculture.dto.auth.RegisterDTO;
import com.agriculture.dto.auth.ResetPasswordDTO;
import com.agriculture.dto.auth.VerifyIdentityDTO;
import com.agriculture.mapper.UserMapper;
import com.agriculture.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;

    public Response<?> login(LoginDTO loginDTO) {
        try {
            // 参数校验
            if (loginDTO.getUsername() == null || loginDTO.getPassword() == null) {
                return Response.error("用户名或密码不能为空");
            }

            // 查询用户
            User user = userMapper.findByUsername(loginDTO.getUsername());
            if (user == null || !loginDTO.getPassword().equals(user.getPassword())) {
                return Response.error("用户名或密码错误");
            }

            // 验证角色
            if (loginDTO.getRole() != null && !loginDTO.getRole().equals(user.getRole())) {
                return Response.error("用户角色不匹配");
            }

            if (!"active".equals(user.getStatus())) {
                return Response.error("账号已被禁用");
            }

            // 生成token
            String token = jwtUtil.generateToken(user);

            // 更新最后登录时间
            userMapper.updateLoginTime(user.getUserId());

            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            
            // 构建完整的用户信息
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", user.getUserId());
            userInfo.put("username", user.getUsername());
            userInfo.put("role", user.getRole());
            userInfo.put("fullName", user.getFullName());
            userInfo.put("phone", user.getPhoneNumber());
            userInfo.put("email", user.getEmail());
            userInfo.put("address", user.getAddress());
            
            result.put("token", token);
            result.put("user", userInfo);

            return Response.success("登录成功", result);
        } catch (Exception e) {
            return Response.error("登录失败: " + e.getMessage());
        }
    }

    @Transactional
    public Response<?> register(RegisterDTO registerDTO) {
        try {
            // 参数校验
            if (registerDTO.getUsername() == null || registerDTO.getPassword() == null) {
                return Response.error("用户名或密码不能为空");
            }

            // 检查用户名是否已存在
            if (userMapper.findByUsername(registerDTO.getUsername()) != null) {
                return Response.error("用户名已存在");
            }

            // 创建新用户
            User user = new User();
            user.setUsername(registerDTO.getUsername());
            user.setPassword(registerDTO.getPassword());
            user.setFullName(registerDTO.getFullName());
            user.setRole(registerDTO.getRole());
            user.setPhoneNumber(registerDTO.getPhoneNumber());
            user.setEmail(registerDTO.getEmail());
            user.setAddress(registerDTO.getAddress());
            user.setStatus("active");

            userMapper.insert(user);

            return Response.success("注册成功", convertToDTO(user));
        } catch (Exception e) {
            return Response.error("注册失败: " + e.getMessage());
        }
    }

    public Response<?> resetPassword(ResetPasswordDTO resetDTO) {
        try {
            // 参数校验
            if (resetDTO.getUsername() == null || resetDTO.getNewPassword() == null) {
                return Response.error("用户名或新密码不能为空");
            }

            // 查询用户
            User user = userMapper.findByUsername(resetDTO.getUsername());
            if (user == null) {
                return Response.error("用户不存在");
            }

            // 验证验证码
            if (!verifyCode(resetDTO.getVerificationCode())) {
                return Response.error("验证码无效或已过期");
            }

            // 更新密码
            user.setPassword(resetDTO.getNewPassword());
            userMapper.update(user);

            return Response.success("密码重置成功", null);
        } catch (Exception e) {
            return Response.error("密码重置失败: " + e.getMessage());
        }
    }

    public Response<?> verifyIdentity(VerifyIdentityDTO verifyDTO) {
        try {
            // 参数校验
            if (verifyDTO.getUsername() == null) {
                return Response.error("用户名不能为空");
            }

            // 查询用户
            User user = userMapper.findByUsername(verifyDTO.getUsername());
            if (user == null) {
                return Response.error("用户不存在");
            }

            // 验证邮箱或手机号
            if (!user.getEmail().equals(verifyDTO.getEmail()) && 
                !user.getPhoneNumber().equals(verifyDTO.getPhoneNumber())) {
                return Response.error("验证信息不匹配");
            }

            // 生成验证码并发送
            String code = generateVerificationCode();
            if (verifyDTO.getEmail() != null) {
                sendEmailVerificationCode(verifyDTO.getEmail(), code);
            } else {
                sendSmsVerificationCode(verifyDTO.getPhoneNumber(), code);
            }

            return Response.success("验证码已发送", null);
        } catch (Exception e) {
            return Response.error("身份验证失败: " + e.getMessage());
        }
    }

    // 辅助方法
    private boolean verifyCode(String code) {
        // TODO: 实现验证码验证逻辑
        return true;
    }

    private String generateVerificationCode() {
        // TODO: 实现验证码生成逻辑
        return "123456";
    }

    private void sendEmailVerificationCode(String email, String code) {
        // TODO: 实现邮件发送逻辑
    }

    private void sendSmsVerificationCode(String phoneNumber, String code) {
        // TODO: 实现短信发送逻辑
    }

    private Map<String, Object> convertToDTO(User user) {
        Map<String, Object> userDTO = new HashMap<>();
        userDTO.put("userId", user.getUserId());
        userDTO.put("username", user.getUsername());
        userDTO.put("role", user.getRole());
        userDTO.put("email", user.getEmail());
        // 不返回密码，确保安全
        return userDTO;
    }
} 